# -*- coding:utf-8 -*-
from twisted.internet import defer, task
from server.util import errors, mySocket, myHtml, stringUtil
import hmac, traceback


class serviceFilter(object):
    def __init__(self, handler, tin):
        self.handler = handler
        self.tin = tin
        self.socket_key = "2e0160e078aa4b925e62b20610378253"
        self.http_key = "83f229f58f5a79ddeaded563a76c5e58"

    def requestCheck(self, data, socket):  # 请求判断 socket: 本次请求来源
        d = defer.Deferred()
        d.addCallbacks(self.returnCheck, self.unLegitimate)
        d.addErrback(self.unSendData)

        try:
            if socket.transport.getPeer().type == 'TCP':
                success, arr = mySocket.ifSocket(self.socket_key, data)
                if success:
                    self.handler.data_handler(arr, d, socket)
                else:
                    d.errback(errors.Illegal("error[1001]非法的数据: [%s]" % data))
            elif socket.transport.getPeer().type == 'HTTP':
                myHtml.ifHtml(self, data, d, socket)
            else:
                d.errback(errors.Illegal("error[1000]无法辨认的请求类型: From[%s]\n Message[%s]") % (socket.transport.getPeer(), data))

        except Exception, e:
            d.errback(errors.Illegal("error[100]意外的错误: %s" % traceback.format_exc()))

    def returnCheck(self, parm):  # 返回类型检查
        if parm[0] == 1:  # 需要返回信息
            data, socket = parm[1], self.tin.get(parm[2])
            # 加密
            sendData = ",".join(tuple(data))
            hmacKey = hmac.new(self.socket_key)
            hmacKey.update(sendData)
            sh = hmacKey.hexdigest()
            sendData = sendData + "," + sh

            length = str(len(sendData))
            sendData = length + sendData

            # import time
            # t = time.time()
            # for each in xrange(80000000):
            #     pass
            # o = time.time()
            # show = o-t
            # print show

            socket.send_Data(sendData)
        elif parm[0] == 2:  # 不需要返回信息
            raise
        elif parm[0] == 3:  # 关闭socket
            baId = parm[2]
            lb = stringUtil.redis_key_name(baId)
            self.handler.re.lset(lb, 1, "lose")  # 将状态更新为失去
            socket = self.tin.get(baId)
            socket.transport.loseConnection()
            raise

    # @logs.logged("INFO")
    def unSendData(self, message):  # 不返回任何数据
        print "------------------------request end-----------------------------------"
        pass

    # @logs.logged("WARN")
    def unLegitimate(self, message):  # errback
        print message.value.message
        raise
